package com.ezandroid.library.network.util;

import android.os.Environment;
import android.os.StatFs;
import android.text.TextUtils;

import java.io.File;

/**
 * SDCardUtil
 *
 * @author like
 * @date 2016-05-13
 */
public class SDCardUtil {

    public static final int SD_NO_SPACE = 0;
    public static final int SD_NO_SD = 1;
    public static final int SD_OK = 2;

    /**
     * sdcard是否可读
     *
     * @return
     */
    public static boolean isStorageReadable() {
        return Environment.getExternalStorageDirectory().canRead();
    }

    /**
     * sdcard是否可写
     *
     * @return
     */
    public static boolean isStorageWriteable() {
        return Environment.getExternalStorageDirectory().canWrite();
    }

    /**
     * sdcard是否存在
     *
     * @return
     */
    public static boolean hasExternalStorage() {
        return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
    }

    /**
     * 判断存储空间是否足够
     *
     * @param needSize
     * @return
     */
    public static int checkExternalSpace(long needSize) {
        int flag = SD_OK;
        if (hasExternalStorage()) {
            File sdcardDir = Environment.getExternalStorageDirectory();
            StatFs sf = new StatFs(sdcardDir.getPath());
            long blockSize = sf.getBlockSize();
            long availCount = sf.getAvailableBlocks();
            long restSize = availCount * blockSize;
            if (restSize > needSize) {
                flag = SD_OK;
            } else {
                flag = SD_NO_SPACE;
            }
        } else {
            flag = SD_NO_SD;
        }
        return flag;
    }

    /**
     * 文件是否存在
     *
     * @param filePath 文件全路径
     * @return
     */
    public static boolean isFileExist(String filePath) {
        if (!TextUtils.isEmpty(filePath)) {
            File file = new File(filePath);
            if (file.exists() && file.isFile()) {
                if (file.length() > 0) {
                    return true;
//                } else {
//                    file.delete();
                }
            }
        }
        return false;
    }

    /**
     * 文件是否存在
     *
     * @param file
     * @return
     */
    public static boolean isFileExist(File file) {
        if (file != null) {
            if (file.exists() && file.isFile()) {
                if (file.length() > 0) {
                    return true;
//                } else {
//                    file.delete();
                }
            }
        }
        return false;
    }
}
